﻿using ASmile.Com;
using ASmile.Helpers;
using ASmile.Extend;

namespace ASmile.Win
{
    /// <summary>
    /// 自定义对象对象工厂
    /// </summary>
    public class ObjectFactory
    {
        public class LoginSession : ILoginSession
        {
            static LoginSession()
            {
                _User = new Com.LoginUser();
                LoginUser.OnResetUser += LoginUser_OnResetUser;
            }

            static bool IsReset = false;

            private static void LoginUser_OnResetUser()
            {
                IsReset = true;
            }

            static string Host { get; } = HostHelper.GetIp();

            public string LoginHost => Host;

            static Com.LoginUser _User { get; }

            public Com.LoginUser CurrUser //=> _User;
            {
                get
                {
                    if (IsReset)
                    {
                        _User.UserId = LoginUser.UserId;
                        _User.UserName = LoginUser.UserName;
                        _User.DeptId = LoginUser.DeptId;
                        _User.DeptName = LoginUser.DeptName;
                        _User.IsManager = LoginUser.IsManager ?? false;
                        _User.RoleId = LoginUser.RoleId;
                        _User.RoleName = LoginUser.RoleName;
                        IsReset = false;
                    }
                    return _User;
                }
            }
        }

        static LoginSession Session { get; } = new LoginSession();

        /// <summary>
        /// 根据服务名获取指定类型对象
        /// </summary>
        public static T GetObject<T>(string name) where T : class
        {
            var obj = Objects.ObjectLoader.GetObject<T>(name);
            if (obj is ILoginSessionSet loginState && Session.CurrUser.UserId != null)
            {
                loginState.SetLoginSession(Session);
            }
            return obj;
        }
    }
}